package org.finesys.system.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.finesys.common.constants.CacheConstants;
import org.finesys.common.core.constants.enums.RoleEnum;
import org.finesys.common.core.exception.ErrorCodes;
import org.finesys.common.core.module.DeptDataPermissionEntity;
import org.finesys.common.core.module.R;
import org.finesys.common.core.util.MessageUtil;
import org.finesys.common.dataPermission.enums.DataScopeEnum;
import org.finesys.common.excel.exception.ErrorMessage;
import org.finesys.common.mp.core.service.impl.BaseServiceImpl;
import org.finesys.common.security.core.module.AuthUser;
import org.finesys.system.api.dto.DeptDTO;
import org.finesys.system.api.entity.SysRole;
import org.finesys.system.api.tenant.SysTenant;
import org.finesys.system.api.vo.RoleExcelVO;
import org.finesys.system.convert.SysRoleConvert;
import org.finesys.system.mapper.SysRoleMapper;
import org.finesys.system.service.SysDeptService;
import org.finesys.system.service.SysRoleMenuService;
import org.finesys.system.service.SysRoleService;
import org.finesys.system.service.SysUserRoleService;
import org.finesys.system.service.tenant.SysTenantService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;


@Service
@RequiredArgsConstructor
@Slf4j
public class SysRoleServiceImpl extends BaseServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    private final SysUserRoleService sysUserRoleService;
    private final SysRoleMenuService sysRoleMenuService;
    private final SysDeptService sysDeptService;
    private final SysTenantService sysTenantService;

    @Override
    @Caching(evict = {
            @CacheEvict(value = CacheConstants.ROLE_DETAILS, key = "#roleId"),
            @CacheEvict(value = CacheConstants.MENU_DETAILS, key = "#roleId"),
            @CacheEvict(value = CacheConstants.USER_ROLE_DETAILS, allEntries = true),
            @CacheEvict(value = CacheConstants.IS_SUPER_ADMIN, allEntries = true)
    })
    public Boolean removeRoleById(Long roleId) {
        /**查询角色信息*/
        SysRole sysRole = baseMapper.selectById(roleId);
        //是否内置角色
        Assert.state(!RoleEnum.isSystem(sysRole.getRoleCode()), MessageUtil.getMessage(ErrorCodes.SYS_DICT_DELETE_SYSTEM));
        // 删除角色菜单关联信息
        sysRoleMenuService.deleteRoleMenuByRoleId(roleId);
        // 删除角色用户关联信息
        sysUserRoleService.deleteUserRoleByRoleId(roleId);
        // 删除角色信息
        return baseMapper.deleteById(roleId) > 0;
    }

    @Override
    @Cacheable(value = CacheConstants.IS_SUPER_ADMIN, key = "#userId")
    public Boolean isSupperAdmin(Long userId) {
        List<SysRole> roleList = baseMapper.findRolesByUserId(userId);
        return roleList.stream().anyMatch(sysRole -> RoleEnum.SUPER_ADMIN.getType().equals(sysRole.getRoleCode()));
    }

    @Override
    @Cacheable(value = CacheConstants.USER_ROLE_DETAILS, key = "#userId")
    public List<SysRole> findRolesByUserId(Long userId) {
        return baseMapper.findRolesByUserId(userId);
    }

    /**
     * 获取用户数据权限信息
     */
    @Override
    @Cacheable(value = CacheConstants.DATA_SCOPE, key = "#authUser.userId")
    public DeptDataPermissionEntity getDataPermission(AuthUser authUser) {
        DeptDataPermissionEntity deptDataPermissionEntity = new DeptDataPermissionEntity();
        //获取用户角色信息
        List<SysRole> roleList = findRolesByUserId(authUser.getUserId());
        roleList.stream().forEach(sysRole -> {
            // 为空时，跳过
            if (ObjectUtils.isEmpty(sysRole.getDataScope())) {
                return;
            }
            // 情况一，ALL
            if (DataScopeEnum.ALL.getScope().equals(sysRole.getDataScope())) {
                deptDataPermissionEntity.setAll(true);
                return;
            }
            // 情况二，DEPT_CUSTOM
            if (Objects.equals(DataScopeEnum.DEPT_CUSTOM.getScope(), sysRole.getDataScope())) {
                CollUtil.addAll(deptDataPermissionEntity.getDeptIds(), sysRole.getDataScopeDeptIds());
                CollUtil.addAll(deptDataPermissionEntity.getDeptIds(), authUser.getDeptId());
                return;
            }
            // 情况三，DEPT_ONLY
            if (Objects.equals(DataScopeEnum.DEPT_ONLY.getScope(), sysRole.getDataScope())) {
                deptDataPermissionEntity.getDeptIds().add(authUser.getDeptId());
                return;
            }
            // 情况四，DEPT_DEPT_AND_CHILD
            if (Objects.equals(DataScopeEnum.DEPT_AND_CHILD.getScope(), sysRole.getDataScope())) {
                //获取子部门信息
                List<DeptDTO> deptList = sysDeptService.findChildDepts(authUser.getDeptId());
                CollUtil.addAll(deptDataPermissionEntity.getDeptIds(), deptList.stream().map(DeptDTO::getDeptId).collect(Collectors.toList()));
                //添加本部门
                deptDataPermissionEntity.getDeptIds().add(authUser.getDeptId());
                return;
            }
            // 情况五，SELF
            if (Objects.equals(DataScopeEnum.SELF.getScope(), sysRole.getDataScope())) {
                deptDataPermissionEntity.setSelf(true);
                return;
            }
            // 未知情况，error log 即可
            log.error("[getDeptDataPermission][LoginUser({}) roleDO({}) 无法处理]", authUser.getUserId(), deptDataPermissionEntity);
        });
        return deptDataPermissionEntity;
    }


    @Override
    public R<?> importRole(List<RoleExcelVO> excelVOList, BindingResult bindingResult) {
        // 通用校验获取失败的数据
        List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();

        // 个性化校验逻辑
        List<SysRole> roleList = this.list();
        List<SysTenant> tenantList = sysTenantService.list();
        // 执行数据插入操作 组装 RoleDto
        for (RoleExcelVO excel : excelVOList) {
            Set<String> errorMsg = new HashSet<>();
            // 检验角色名称或者角色编码是否存在
            boolean existRole = roleList.stream()
                    .anyMatch(sysRole -> excel.getRoleName().equals(sysRole.getRoleName())
                            || excel.getRoleCode().equals(sysRole.getRoleCode()));

            if (existRole) {
                errorMsg.add(MessageUtil.getMessage(ErrorCodes.SYS_ROLE_NAMEORCODE_EXISTING, excel.getRoleName(),
                        excel.getRoleCode()));
            }
            // 判断输入的租户名称列表是否合法
            Optional<SysTenant> tenantOptional = tenantList.stream()
                    .filter(tenant -> excel.getTenantName().equals(tenant.getName()))
                    .findFirst();
            if (!tenantOptional.isPresent()) {
                errorMsg.add(MessageUtil.getMessage(ErrorCodes.SYS_TENANT_TENANTNAME_INEXISTENCE, excel.getTenantName()));
            }

            // 数据合法情况
            if (CollUtil.isEmpty(errorMsg)) {
                insertExcelRole(excel, tenantOptional);
            } else {
                // 数据不合法情况
                errorMessageList.add(new ErrorMessage(excel.getLineNum(), errorMsg));
            }
        }
        if (CollUtil.isNotEmpty(errorMessageList)) {
            return R.failed(errorMessageList);
        }
        return R.success();
    }

    private void insertExcelRole(RoleExcelVO excel, Optional<SysTenant> tenantOptional) {
        SysRole sysRole = SysRoleConvert.INSTANCE.convert(excel);
        Long tenantId = tenantOptional.get().getTenantId();
        sysRole.setTenantId(tenantId == null ? 1L : tenantId);
        this.save(sysRole);
    }

    @Override
    public List<RoleExcelVO> listRole() {
        List<SysRole> roleList = baseMapper.selectList(Wrappers.emptyWrapper());
        List<SysTenant> tenantList = sysTenantService.list();
        Map<Long, String> tenantMap = tenantList.stream().collect(Collectors.toMap(SysTenant::getTenantId, SysTenant::getName, (k1, k2) -> k1));
        return roleList.stream().map(sysRole -> {
            RoleExcelVO roleExcelVO = SysRoleConvert.INSTANCE.convert(sysRole);
            roleExcelVO.setTenantName(tenantMap.get(sysRole.getTenantId()));
            return roleExcelVO;
        }).collect(Collectors.toList());
    }
}
